package com.qny.ai.config;

import com.qny.ai.websocket.SignalingHandler;
import com.qny.ai.websocket.VoiceHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    private final SignalingHandler signalingHandler;
    private final VoiceHandler voiceHandler;

    public WebSocketConfig(SignalingHandler signalingHandler, VoiceHandler voiceHandler) {
        this.signalingHandler = signalingHandler;
        this.voiceHandler = voiceHandler;
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(signalingHandler, "/ws/signaling").setAllowedOrigins("*");
        registry.addHandler(voiceHandler, "/ws/voice").setAllowedOrigins("*");
    }

    // 提高服务端文本/二进制消息缓存，避免 1009（message too big）
    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxTextMessageBufferSize(512 * 1024);   // 512KB
        container.setMaxBinaryMessageBufferSize(2 * 1024 * 1024); // 2MB
        container.setAsyncSendTimeout(30_000L);
        container.setMaxSessionIdleTimeout(60_000L);
        return container;
    }
}


